<!--
 * @Author: wu_zh
 * @Date: 2021-09-16 15:05:40
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-03-16 17:03:50
 * @Descripttion: 
-->
<template>
  <div v-bind="$attrs">
    <div class="data-config-container">
      <fks-form :model="dataConfig" label-position="right">
        <fks-form-item label="关联表单">
          <fks-select
            v-model="dataConfig.relateForm"
            placeholder="请选择关联表单"
            @change="relateFormChange"
          >
            <fks-option
              v-for="item in formArr"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </fks-option>
          </fks-select>
        </fks-form-item>
        <fks-form-item
          v-if="dataConfig.relateForm && showRelateForm"
          label="表单字段"
        >
          <div v-if="tagAttribute == 'associate-data'">
            <div
              class="no-matching"
              v-if="relateFormFields.length == 0"
              style="text-align: center"
            >
              暂无表单字段
            </div>
            <fks-checkbox-group v-model="checkedRelateFormFields">
              <fks-checkbox
                style="display: block"
                v-for="field in relateFormFields"
                :label="field.field"
                :key="field.field"
                >{{ field.name }}</fks-checkbox
              >
            </fks-checkbox-group>
          </div>
          <div v-else>
            <fks-select v-model="dataConfig.relateFormFields">
              <fks-option
                v-for="field in relateFormFields"
                :key="field.field"
                :label="field.name"
                :value="field.field"
              >
              </fks-option>
            </fks-select>
          </div>
        </fks-form-item>
        <fks-form-item
          v-if="dataConfig.relateForm && showRelateForm"
          label="数据过滤"
        >
          <fks-button @click="filterVisible = true">{{
            conditionList.length > 0 ? '已添加过滤条件' : '添加过滤条件'
          }}</fks-button>
        </fks-form-item>
        <fks-form-item
          label="参数映射"
          v-if="
            tagAttribute !== 'select' && dataConfig.relateForm && showRelateForm
          "
        >
          <fks-button @click="addMappingRules">{{
            dataConfig.matchingParams.length > 0 &&
            dataConfig.matchingParams[0].sourceField &&
            dataConfig.matchingParams[0].targetField
              ? '已添加映射规则'
              : '添加映射规则'
          }}</fks-button>
        </fks-form-item>
      </fks-form>
    </div>
    <fks-dialog
      title="添加过滤条件"
      :visible="filterVisible"
      @open="open"
      @close="close"
    >
      <div class="config-main-area" v-if="relateComponentList.length > 0">
        <!-- 条件组弹窗 -->
        <div v-if="conditionVisiblity">
          <div
            class="condition-config"
            v-for="(groupItem, groupIndex) in conditionList"
            :key="groupIndex"
          >
            <p class="group-or" v-if="groupIndex > 0">{{ LANG.OR }}</p>
            <div class="condition-group">
              <div class="condition-group-title">
                <span>{{ LANG.ADD_CONDITION }}</span>
                <i
                  class="iconfont fks-icon-delete"
                  @click="delGroup(groupItem.id)"
                ></i>
              </div>
              <div class="condition-group-main">
                <!-- 条件 -->
                <div
                  class="condition-grouorp-item"
                  v-for="(conditionItem, index) in groupItem.list"
                  :key="index"
                >
                  <div class="group-main-title">
                    <span v-if="index === 0">{{ LANG.WHEN }}</span>
                    <span v-if="index !== 0">{{ LANG.AND }}</span>
                    <i
                      class="iconfont fks-icon-delete"
                      v-show="groupItem.list.length > 1"
                      @click="delCondition(conditionItem)"
                    ></i>
                  </div>
                  <!-- 组件下拉 -->
                  <fks-select
                    v-model="conditionItem.module"
                    :placeholder="LANG.PLEASE_SELECT"
                    @change="
                      changeModule(
                        $event,
                        groupItem.id,
                        conditionItem.conditionId
                      )
                    "
                  >
                    <fks-option
                      v-for="item in relateComponentList"
                      :key="item.__vModel__"
                      :label="item.__config__.label"
                      :value="item.__vModel__"
                    >
                    </fks-option>
                  </fks-select>
                  <!-- 配置2-->
                  <!-- <fks-select 
                    v-model="conditionItem.checkboxType"
                    :placeholder="LANG.PLEASE_SELECT"
                    v-if="conditionItem.tag === 'fks-checkbox-group'"
                    @change="changeCheckboxType(conditionItem)"
                  >
                    <fks-option
                      v-for="item in checkboxOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </fks-option>
                  </fks-select> -->
                  <!-- 选择类组件配置-->
                  <fks-select
                    v-model="conditionItem.config"
                    @change="selectConditionChange()"
                    :placeholder="LANG.PLEASE_SELECT"
                    :multiple="
                      conditionItem.multiple ||
                      conditionItem.tagAttribute == 'check-box'
                    "
                    v-if="
                      [
                        'fks-input',
                        'fks-input-number',
                        'fks-org-selector'
                      ].indexOf(conditionItem.tag) == -1 &&
                      conditionItem.checkboxType !== 1
                    "
                  >
                    <fks-option
                      v-for="configItem in conditionItem.configList"
                      :key="configItem.value"
                      :label="configItem.label"
                      :value="configItem.value"
                    >
                    </fks-option>
                  </fks-select>
                  <!-- <fks-select
                    v-model="conditionItem.config"
                    :placeholder="LANG.PLEASE_SELECT"
                    multiple
                    v-if="
                      conditionItem.tag !== 'fks-input' &&
                      conditionItem.checkboxType === 1
                    "
                  >
                    <fks-option
                      v-for="configItem in conditionItem.configList"
                      :key="configItem.value"
                      :label="configItem.label"
                      :value="configItem.value"
                    >
                    </fks-option>
                  </fks-select> -->
                  <!-- 数字金额组件条件配置-->
                  <fks-select
                    v-model="conditionItem.amountConditon"
                    placeholder="请选择"
                    v-if="
                      conditionItem.tagAttribute === 'number' ||
                      conditionItem.tagAttribute === 'count'
                    "
                  >
                    <fks-option
                      v-for="item in amountConditonOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </fks-option>
                  </fks-select>
                  <!-- 选部门组件条件配置 -->
                  <fks-org-selector
                    @change="selectConditionChange()"
                    v-if="conditionItem.tagAttribute === 'org-selector'"
                    :deptId.sync="conditionItem.deptIdConfig"
                    :deptName.sync="conditionItem.deptNameConfig"
                  >
                  </fks-org-selector>
                  <fks-input
                    type="number"
                    @change="selectConditionChange()"
                    :placeholder="LANG.PLEASE_ENTER + LANG.NUMBER"
                    v-if="
                      conditionItem.tagAttribute === 'number' ||
                      conditionItem.tagAttribute === 'count'
                    "
                    v-model="conditionItem.numberConfig"
                  ></fks-input>
                  <fks-input
                    @change="selectConditionChange()"
                    :placeholder="LANG.PLEASE_ENTER + LANG.CONTENT"
                    v-if="
                      conditionItem.tagAttribute === 'input' ||
                      conditionItem.tagAttribute === 'comment'
                    "
                    v-model="conditionItem.inputConfig"
                  ></fks-input>
                </div>
                <p>
                  <fks-button
                    icon="fks-icon-circle-plus-outline"
                    @click="addConditionItem(groupItem.id)"
                    >{{ LANG.ADD_CONDITION }}</fks-button
                  >
                </p>
              </div>
            </div>
          </div>
        </div>
        <!-- 添加条件组 -->
        <div style="margin-top: 10px">
          <fks-button
            icon="fks-icon-circle-plus-outline"
            @click="addConditionGroup"
            >{{ LANG.ADD_CONDITION_GROUP }}</fks-button
          >
        </div>
      </div>
      <div v-else style="text-align: center">请先选择有字段的关联表单</div>
      <span slot="footer" class="dialog-footer">
        <fks-button @click="close()">取 消</fks-button>
        <fks-button type="primary" @click="confirm()">确 定</fks-button>
      </span>
    </fks-dialog>
    <fks-dialog
      title="添加映射规则"
      :visible="mapVisible"
      @open="openMapDialog"
      @close="closeMapDialog"
    >
      <div
        class="no-matching"
        v-if="dataConfigCopy.matchingParams.length == 0"
        style="text-align: center"
      >
        暂无参数映射，点击添加
      </div>
      <div
        class="params-setting"
        v-for="(param, index) in dataConfigCopy.matchingParams"
        :key="index"
        style="margin-bottom: 10px"
      >
        <fks-select
          v-model="param.targetField"
          placeholder="请选择当前表单字段"
          size="small"
          style="width: 178px"
          @change="targetFieldChange($event, index)"
        >
          <fks-option
            v-for="item in currentFormFields"
            :key="item.field"
            :label="item.name"
            :value="item.field"
          >
          </fks-option>
        </fks-select>
        <span style="margin: 0 10px">=</span>
        <fks-select
          size="small"
          v-model="param.sourceField"
          placeholder="请先选择关联表单字段"
          no-data-text="无相同组件类型字段"
          style="width: 178px"
        >
          <fks-option
            v-for="item in param.filterRelateFormFields"
            :key="item.field"
            :label="item.name"
            :value="item.field"
          >
          </fks-option>
        </fks-select>
        <i
          class="iconfont fks-icon-delete"
          style="
            padding: 10px;
            color: #ff4d4f;
            cursor: pointer;
            margin-left: 5px;
          "
          @click="delMatchingParams(index)"
        ></i>
      </div>
      <fks-button ref="addMatchRef" @click="addMatchingParams">添加</fks-button>
      <span slot="footer" class="dialog-footer">
        <fks-button @click="closeMapDialog()">取 消</fks-button>
        <fks-button type="primary" @click="confirmMaprules()">确 定</fks-button>
      </span>
    </fks-dialog>
  </div>
</template>

<script>
import {
  getField,
  getDesignedModule
} from './api'
export default {
  props: {
    dataConfig: {
      type: Object,
      default: () => {
        return {}
      }
    },
    currentComponentLists: {
      type: Array,
      default: () => {
        return []
      }
    },
    formArr: {
      type: Array,
      default: () => {
        return []
      }
    },
    tagAttribute: '',
    currentModel: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  components: {},
  data() {
    return {
      loading: false,
      form: {
        relateForm: '',
        relateFormFields: [],
        matchingParams: [{}]
      },
      matchingParams: [], // 选中关联表单字段，对应的表单字段数组中的值
      formOptions: [],
      showRelateForm: false,
      relateFormFields: [],
      checkedRelateFormFields: [],
      filterRelateFormFields: [],
      relateComponentList: [], // 关联表单组件数组
      conditionVisiblity: false,
      conditionList: [], //条件组数组
      amountConditonOptions: [
        // 金额条件数组
        {
          label: '小于',
          value: 1
        },
        {
          label: '小于等于',
          value: 2
        },
        {
          label: '大于',
          value: 3
        },
        {
          label: '大于等于',
          value: 4
        },
        {
          label: '等于',
          value: 5
        }
      ],
      dataConfigCopy: {
        relateForm: '',
        relateFormFields: [],
        matchingParams: [{}]
      },
      filterVisible: false,
      mapVisible: false
    }
  },
  computed: {
    currentFormFields() {
      let fieldsArr = []
      this.currentComponentLists.forEach((item) => {
        if (
          item.__vModel__ &&
          item.__config__.tagAttribute !== 'associate-data'
        ) {
          let obj = {}
          obj.field = item.__vModel__
          obj.name = item.__config__.label
          obj.type = item.__config__.tagAttribute
          fieldsArr.push(obj)
        }
      })
      return fieldsArr
    }
  },
  watch: {
    'dataConfig.relateForm': {
      handler(newVal, oldval) {
        if (newVal) {
          if (
            oldval &&
            newVal !== oldval &&
            !this.dataConfig &&
            !this.dataConfig.relateForm
          ) {
            this.checkedRelateFormFields = []
            this.dataConfig.matchingParams = []
            this.conditionList = []
            this.dataConfig.filterCondition = ''
            this.dataConfig.filterExpression = ''
          }

          let formKey = newVal.slice(0, 21)
          getField(formKey).then((res) => {
            if (res.status) {
              this.relateFormFields = res.data || []
              this.conditionList =
                this.dataConfig.filterCondition.length > 0
                  ? JSON.parse(this.dataConfig.filterCondition)
                  : []
              let arr = this.dataConfig.relateFormFields
                ? this.dataConfig.relateFormFields.split(',')
                : []
              // 去除表单中已删除的组件数据
              let filterArr = []
              arr.forEach((item, index) => {
                let isExist = this.relateFormFields.some((obj) => {
                  return obj.field == item
                })
                if (isExist) {
                  filterArr.push(item)
                }
              })
              this.checkedRelateFormFields = filterArr
              this.dataConfig.matchingParams =
                this.dataConfig.matchingParams.filter((item) => {
                  return (
                    this.checkedRelateFormFields.indexOf(item.sourceField) !==
                    -1
                  )
                })
            }
          })

          this.conditionVisiblity = true
          getDesignedModule({ formKey: formKey }).then((res) => {
            if (res.status && res.data) {
              let formDesign = JSON.parse(res.data.formDesign)
              this.relateComponentList = formDesign.fields.filter((item) => {
                return (
                  [
                    'input',
                    'comment',
                    'count',
                    'number',
                    'select',
                    'radio',
                    'check-box',
                    'user-selector',
                    'org-selector',
                    'notify'
                  ].indexOf(item.__config__.tagAttribute) !== -1
                )
              })
              this.showRelateForm = true
            }
          })
        } else {
          this.relateComponentList = []
          this.relateFormFields = []
        }
      },
      immediate: true
    },
    checkedRelateFormFields(val) {
      this.dataConfig.relateFormFields = val.join()
      this.matchingParams = this.relateFormFields.filter((item) => {
        return val.indexOf(item.field) !== -1
      })
    },
    'checkedRelateFormFields.length': {
      handler(newVal, oldVal) {
        // 删除涉及到参数映射配置的表单字段，参数映射相关配置同步删除
        if (oldVal > newVal) {
          this.dataConfig.matchingParams =
            this.dataConfig.matchingParams.filter((item) => {
              return (
                this.checkedRelateFormFields.indexOf(item.sourceField) !== -1
              )
            })
        }
      }
    },
    currentModel: {
      handler(newVal, oldval) {
        if (oldval && newVal !== oldval) {
          // this.dataConfig.relateFormFields = ''
          let conditionList =
            this.dataConfig.filterCondition.length > 0
              ? JSON.parse(this.dataConfig.filterCondition)
              : []
          this.conditionList = conditionList
          this.checkedRelateFormFields = this.dataConfig.relateFormFields
            ? this.dataConfig.relateFormFields.split(',')
            : []
          this.conditionVisiblity = true
        }
      }
    }
  },
  methods: {
    addMappingRules() {
      this.mapVisible = true
      this.$nextTick(() => {
        this.$refs.addMatchRef.handleClick()
      })
    },
    /**
     * @description: 点击按钮添加一项参数映射
     * @param {*}
     * @return {*}
     */
    addMatchingParams() {
      let matchItem = {
        filterRelateFormFields: [],
        sourceField: '',
        targetField: ''
      }
      this.dataConfigCopy.matchingParams.push(matchItem)
    },
    delMatchingParams(index) {
      this.dataConfigCopy.matchingParams.splice(index, 1)
    },
    /**
     * @description: 改变参数映射配置的当前表单字段
     * @param {*}
     * @return {*}
     */
    targetFieldChange(field, index) {
      let filterType = ''
      this.currentFormFields.forEach((item) => {
        if (item.field == field) {
          filterType = item.type
        }
      })
      this.dataConfigCopy.matchingParams[index].filterRelateFormFields =
        this.matchingParams.filter((item) => {
          return item.tagAttribute == filterType
        })
      this.dataConfigCopy.matchingParams[index].sourceField = ''
      // this.filterRelateFormFields = this.relateFormFields
    },
    /**
     * @description: 数据过滤，关联表单的字段选择修改
     * @param {*}
     * @return {*}
     */
    // filterFieldChange(field, filterItem) {
    // 	console.log(field, filterItem)
    // 	this.currentFormFields.forEach((item) => {
    // 		if (filterItem.field == field) {
    // 			filterItem.tagAttribute = item.type
    // 		}
    // 	})
    // },
    // 添加条件组
    addConditionGroup() {
      let data = {
        id: Math.floor(Math.random() * 10000),
        list: [
          {
            conditionId: Math.floor(Math.random() * 10000),
            tag: this.relateComponentList[0].__config__.tag,
            tagIcon: this.relateComponentList[0].__config__.tagIcon,
            tagAttribute: this.relateComponentList[0].__config__.tagAttribute,
            module: this.relateComponentList[0].__vModel__,
            checkboxType: '',
            config: '',
            configList: this.relateComponentList[0].__slot__
              ? this.relateComponentList[0].__slot__.options
              : [],
            multiple: this.relateComponentList[0].multiple,
            inputConfig: '',
            numberConfig: '',
            deptNameConfig: '',
            deptIdConfig: ''
          }
        ]
      }
      this.conditionList.push(data)
      this.conditionVisiblity = true
    },
    // 添加条件
    addConditionItem(id) {
      let data = {
        conditionId: Math.floor(Math.random() * 10000),
        tag: this.relateComponentList[0].__config__.tag,
        tagIcon: this.relateComponentList[0].__config__.tagIcon,
        tagAttribute: this.relateComponentList[0].__config__.tagAttribute,
        module: this.relateComponentList[0].__vModel__,
        checkboxType: '',
        config: '',
        configList: this.relateComponentList[0].__slot__
          ? this.relateComponentList[0].__slot__.options
          : [],
        multiple: this.relateComponentList[0].multiple,
        inputConfig: '',
        numberConfig: '',
        deptNameConfig: '',
        deptIdConfig: ''
      }
      this.conditionList = this.conditionList.map((item) => {
        item.id === id ? item.list.push(data) : ''
        return item
      })
    },
    //删除条件组
    delGroup(groupId) {
      this.conditionList = this.conditionList.filter((item) => {
        return item.id !== groupId
      })
    },
    // 删除条件
    delCondition(condition) {
      this.conditionList = this.conditionList.map((item) => {
        item.list = item.list.filter((conditionItem) => {
          return conditionItem !== condition
        })
        return item
      })
    },
    // 改变组件
    changeModule(moduleId, groupId, conditionId) {
      this.conditionList = this.conditionList.map((item) => {
        if (item.id === groupId) {
          item.list = item.list.map((conditionItem) => {
            if (conditionItem.conditionId === conditionId) {
              this.relateComponentList.forEach((basicItem) => {
                if (basicItem.__vModel__ === moduleId) {
                  conditionItem.tag = basicItem.__config__.tag
                  conditionItem.tagIcon = basicItem.__config__.tagIcon
                  conditionItem.tagAttribute = basicItem.__config__.tagAttribute
                  conditionItem.inputConfig = ''
                  conditionItem.numberConfig = ''
                  conditionItem.deptNameConfig = ''
                  conditionItem.deptIdConfig = ''
                  conditionItem.config = ''
                  ;(conditionItem.configList = basicItem.__slot__
                    ? basicItem.__slot__.options
                    : []),
                    (conditionItem.multiple = basicItem.multiple)
                }
              })
            }
            return conditionItem
          })
        }
        return item
      })
    },
    saveCondition() {
      // 筛选空
      this.conditionList = this.conditionList.filter((item) => {
        item.list = item.list.filter((i) => {
          return (
            (i.config && !Array.isArray(i.config)) ||
            (i.config && i.config[0]) ||
            i.inputConfig ||
            i.numberConfig ||
            i.deptNameConfig
          )
        })
        return item.list.length > 0
      })
      this.dataConfig.filterCondition = this.conditionList
        ? JSON.stringify(this.conditionList)
        : ''
      let e = ['']
      this.conditionList.forEach((item, index) => {
        if (item.list && item.list.length !== 0) {
          index !== this.conditionList.length - 1 ? e.push('(') : ''
          item.list.forEach((i, number) => {
            if (i.numberConfig) {
              let mark = ''
              switch (i.amountConditon) {
                case 1:
                  mark = '<'
                  break
                case 2:
                  mark = '<='
                  break
                case 3:
                  mark = '>'
                  break
                case 4:
                  mark = '>='
                  break
                default:
                  mark = '=='
              }
              e.push(`${i.module} ${mark} ${i.numberConfig}`)
            } else if (i.config) {
              if (Array.isArray(i.config)) {
                e.push(`${i.module} = [`)
                i.config.forEach((conf, confIndex) => {
                  e.push(`"${conf}"`)
                  confIndex !== i.config.length - 1 ? e.push(`,`) : ''
                })
                e.push(`]`)
              } else {
                e.push(`${i.module} = "${i.config}"`)
              }
            } else if (i.inputConfig) {
              e.push(`${i.module} = "${i.inputConfig}"`)
            } else if (i.deptNameConfig && i.deptIdConfig) {
              e.push(
                `${i.module} = '{"deptId":"${i.deptIdConfig}","deptName":"${i.deptNameConfig}"}'`
              )
            }
            number !== item.list.length - 1 ? e.push('&&') : ''
          })
          index !== this.conditionList.length - 1 ? e.push(')', '||') : ''
        }
      })
      // e.push('}')
      e = e.join('')
      e = e.length < 4 ? '' : e
      this.$set(this.dataConfig, 'filterExpression', e)
    },
    // 关联显示条件改变
    selectConditionChange() {
      // this.saveCondition()
    },
    // 修改关联表单
    relateFormChange() {
      this.dataConfig.relateFormFields = ''
    },
    // 打开弹窗
    open() {
      this.conditionList =
        this.dataConfig.filterCondition.length > 0
          ? JSON.parse(this.dataConfig.filterCondition)
          : []
      this.filterVisible = true
    },
    close() {
      this.filterVisible = false
    },
    openMapDialog() {
      this.dataConfigCopy = JSON.parse(JSON.stringify(this.dataConfig))
      this.mapVisible = true
    },
    closeMapDialog() {
      this.mapVisible = false
    },
    confirm() {
      this.saveCondition()
      this.filterVisible = false
    },
    confirmMaprules() {
      this.dataConfig.matchingParams = JSON.parse(
        JSON.stringify(this.dataConfigCopy.matchingParams)
      )
      this.mapVisible = false
    }
  },
  mounted() {
    // 调用watch里面的逻辑，防止切换绑定相同表单的关联组件或者下拉框不更新
    this.dataConfig.relateForm = this.dataConfig.relateForm
  }
}
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类
.config-main-area {
  margin: 0 20px;
}
.condition-btn {
  position: absolute;
  bottom: 0;
  left: 0;
  display: flex;
  justify-content: flex-end;
  width: 100%;
  padding: 16px 24px;
  border-top: 1px solid #eee;
  background: #fff;
}
.condition-drawer {
  .form-area {
    margin: 20px;
    ::v-deep .fks-form {
      margin: 0;
      font-size: 16px;
    }
  }
}
.condition-drawer {
  ::v-deep .fks-drawer__body {
    overflow: auto;
  }
}
.group-or {
  padding: 0 12px;
  font-size: 14px;
}
.condition-group {
  border-radius: 4px;
  border: 1px solid #e4e5e7;
  box-sizing: border-box;
  line-height: 36px;
  font-size: 14px;
  .condition-group-title {
    background-color: #f4f6f8;
    padding: 0 12px;
    height: 36px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    i {
      color: #9ca2a9;
      font-size: 16px;
      line-height: 36px;
      &:hover {
        color: #1890ff;
        cursor: pointer;
      }
    }
  }
  .condition-group-main {
    padding: 0 12px;
    width: 100%;
    ::v-deep .fks-select {
      width: 100%;
      margin-bottom: 16px;
    }
    .group-main-title {
      color: #9ca2a9;
      display: flex;
      justify-content: space-between;
      i {
        font-size: 16px;
        line-height: 36px;
        &:hover {
          color: #1890ff;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
